package com.ruoyi.web.controller.app;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.Usertree;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.ResponseResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.BusiException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.biz.UserRateBizService;
import com.ruoyi.system.domain.Cash;
import com.ruoyi.system.dto.AddMemberDto;
import com.ruoyi.system.dto.UserRateDto;
import com.ruoyi.system.dto.UserUpdatePwdDto;
import com.ruoyi.system.service.BankService;
import com.ruoyi.system.service.CashService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.UserTreeService;
import com.ruoyi.system.vo.MemberNumVo;
import com.ruoyi.system.vo.MemberVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Api(tags = "用户端:用户相关接口")
@RestController
@RequestMapping("/app/user")
public class UserController extends AppController {
    @Resource
    private UserTreeService userTreeService;
    @Resource
    private CashService cashService;
    @Resource
    private ISysUserService userService;

    @Autowired
    private TokenService tokenService;

    /**
     * 重置密码
     */

    private void checkPwd(String password) {

        Pattern compile = Pattern.compile(".*[0-9a-zA-z].*");
        Matcher matcher = compile.matcher(password);
        boolean b = matcher.matches();
        if (!b) {
            throw new BusiException("请输入包含字母和数字的密码");
        }
    }

    @PostMapping("/updatePwd")
    public ResponseResult updatePwd(@Valid @RequestBody UserUpdatePwdDto userUpdatePwdDto) {
        checkPwd(userUpdatePwdDto.getNewPwd());
        Long userId = this.getUserId();
        SysUser user = this.userService.check(userId);
        if (!SecurityUtils.matchesPassword(userUpdatePwdDto.getOldPwd(), user.getPassword())) {
            return this.setErrorResult("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(userUpdatePwdDto.getNewPwd(), user.getPassword())) {
            return this.setErrorResult("新密码不能与旧密码相同");
        }
        if (userService.resetUserPwd(user.getUserName(), SecurityUtils.encryptPassword(userUpdatePwdDto.getNewPwd())) > 0) {
            // 更新缓存用户密码
            // 更新缓存用户密码
            LoginUser loginUser = this.getLoginUser();
            loginUser.getUser().setPassword(SecurityUtils.encryptPassword(userUpdatePwdDto.getNewPwd()));
            tokenService.setLoginUser(loginUser);
            return setSuccessResult();
        }
        return setErrorResult("修改密码异常，请联系管理员");
    }


    @ApiOperation(value = "获取用户信息")
    @GetMapping("getByUserId")
    public ResponseResult<MemberNumVo> getByUserId(Long userId) {
        SysUser user = this.userService.check(userId);
        return this.setSuccessResult(user);
    }

    @Resource
    BankService bankService;
    @Log(title = "开始抢单", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "开始抢单")
    @RequestMapping("start")
    public ResponseResult<MemberNumVo> start() {
        Long userId = this.getUserId();
        SysUser user = this.userService.check(userId);
        if (StrUtil.isBlank(user.getRandomSecretKey())) {
            user.setOrderStatus(0);
            this.userService.updateDomain(user);
            return this.setErrorResult("请前往个人中心绑定谷歌");
        }
        user.setOrderStatus(1);
        user.setOrderStatusTime(new Date());
        this.userService.updateDomain(user);
        return this.setSuccessResult(user);
    }
    @Log(title = "停止抢单", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "停止抢单")
    @RequestMapping("stop")
    public ResponseResult<MemberNumVo> stop() {
        Long userId = this.getUserId();
        SysUser user = this.userService.check(userId);

        user.setOrderStatus(0);
        user.setOrderStatusTime(new Date());
        this.userService.updateDomain(user);
        return this.setSuccessResult(user);
    }

    @ApiOperation(value = "开始/停止抢单")
    @RequestMapping("updateStatus")
    public ResponseResult<MemberNumVo> updateStatus() {
        Long userId = this.getUserId();
        SysUser user = this.userService.check(userId);
        if (user.getOrderStatus() == 1) {
            user.setOrderStatus(0);
        } else {
            // bankService.
            user.setOrderStatus(1);


        }
        user.setOrderStatusTime(new Date());
        this.userService.updateDomain(user);
        return this.setSuccessResult(user);
    }

    @ApiOperation(value = "统计团队人数以及推荐收益")
    @PostMapping("countMembers")
    public ResponseResult<MemberNumVo> countMembers() {
        Long userId = this.getUserId();
        Cash cash = cashService.getByUserId(userId);
        Usertree usertree = new Usertree();
        usertree.setParentId(userId);
        usertree.setDist(1);
        int one = userTreeService.countByDomain(usertree);
        usertree.setDist(2);
        int two = userTreeService.countByDomain(usertree);
        usertree.setDist(3);
        int three = userTreeService.countByDomain(usertree);
        MemberNumVo memberNumVo = BeanUtil.copyProperties(cash, MemberNumVo.class);
        memberNumVo.setOne(one);
        memberNumVo.setThree(three);
        memberNumVo.setTwo(two);
        return this.setSuccessResult(memberNumVo);
    }

    @ApiOperation(value = "一级粉丝列表")
    @PostMapping("dictMembers")
    public ResponseResult<List<MemberVo>> dictMembers(Integer dist) {
        Long userId = this.getUserId();
        List<MemberVo> members = userService.findMembers(userId, dist);
        return this.setSuccessResult(members);
    }

    @Log(title = "设置点位", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "设置点位,不能相差超过0.2 ")
    @PostMapping("setRate")
    public ResponseResult<MemberNumVo> dictMembers(@Valid @RequestBody UserRateDto userRateDto) {
        Long userId = this.getUserId();

        Usertree usertree = new Usertree();
        usertree.setParentId(userId);
        usertree.setDist(1);
        usertree.setMemberId(userRateDto.getUserId());
        int one = userTreeService.countByDomain(usertree);
        if (one < 1) {
            return this.setErrorResult("数据不存在");
        }
        SysUser parent = userService.check(userId);
        if (parent.getBankRate().compareTo(userRateDto.getBankRate()) < 0 ||
                parent.getBankRate().subtract(userRateDto.getBankRate()).compareTo(new BigDecimal(0.2)) > 0) {
            return this.setErrorResult("银行卡设置点位不能超过0.2");
        }
        if (parent.getZfbRate().compareTo(userRateDto.getZfbRate()) < 0 ||
                parent.getZfbRate().subtract(userRateDto.getZfbRate()).compareTo(new BigDecimal(0.2)) > 0) {
            return this.setErrorResult("支付宝设置点位不能超过0.2");
        }
        SysUser user = userService.check(userRateDto.getUserId());
        user.setBankRate(userRateDto.getBankRate());
        user.setZfbRate(userRateDto.getZfbRate());
        userService.updateDomain(user);
        return this.setSuccessResult();
    }

    @Resource
    private SysLoginService loginService;

    @Resource
    private UserRateBizService userRateBizService;
    @Log(title = "新增下级用户", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "新增下级用户")
    @PostMapping("addMember")
    public ResponseResult<MemberNumVo> addMember(@Valid @RequestBody AddMemberDto addMemberDto) {
        checkPwd(addMemberDto.getPassword());
        Long userId = this.getUserId();
        SysUser parent = this.userService.check(userId);

//        if (parent.getBankRate().compareTo(addMemberDto.getBankRate()) < 0 ||
//                parent.getBankRate().subtract(addMemberDto.getBankRate()).compareTo(new BigDecimal(0.2)) > 0) {
//            return this.setErrorResult("银行卡设置点位不能超过0.2");
//        }
//        if (parent.getZfbRate().compareTo(addMemberDto.getZfbRate()) < 0 ||
//                parent.getZfbRate().subtract(addMemberDto.getZfbRate()).compareTo(new BigDecimal(0.2)) > 0) {
//            return this.setErrorResult("支付宝设置点位不能超过0.2");
//        }

        SysUser sysUser = loginService.addMember(parent, addMemberDto);
        //增加费率
        userRateBizService.addRate(userId, sysUser.getUserId());
        return this.setSuccessResult();
    }

}
